import { defineStore } from 'pinia'
import { store as storeName } from "/@/store";
import {TabModel} from "/@/store/modules/type/TabModel";
import {router} from "/@/router";
import store from 'store'
import NProgress from "nprogress";
export const useMenuStore: any = defineStore({
    id: 'menu',
    state: () => {
        return {
            collapse: false,
            tabBar: [] as TabModel[],
            activateIndex: '',
            cacheList: [] as string[]
        }
    },
    getters: {

    },
    actions: {
      addTab(tab: TabModel){
          let isAdd = true
          //将其他激活菜单取消激活
          this.tabBar.forEach((res: TabModel) => {
              if(tab.title === res.title){
                  isAdd = false
                  res.activate = true
              }else{
                  res.activate = false
              }
          })
          if(isAdd){
              this.tabBar.push(tab)
              //添加组件缓存
              this.cacheList.push(tab.name)
          }
          //开始显示进度条
          NProgress.start()
          //设置菜单栏激活
          this.activateIndex = tab.name
      },
      activateTab(index: number){
          //将其他激活菜单取消激活
          this.tabBar.forEach((res: TabModel) => {
              res.activate = false
          })
          //设置当前tab为激活状态
          this.tabBar[index].activate = true
          //设置菜单栏激活
          this.activateIndex = this.tabBar[index].name
          router.push({
              name: this.activateIndex
          })

      },
      closeTab(index:number){
          let componentIndex = this.cacheList.indexOf(this.tabBar[index].name);
          if(componentIndex != -1){
              this.cacheList.splice(componentIndex,1)
          }
          this.tabBar.splice(index,1)
          if(index > 0){
              this.activateTab(index - 1)
          }
      },
      clear(){
          this.tabBar = []
          this.activateIndex = ''
          this.cacheList = []
      }

    }
})
export function useMenuStoreHook() {
    return useMenuStore(storeName);
}

